<template>
  <div>
    <el-dialog
      :title="flowTitle"
      :visible.sync="detailsVisible"
      width="60%"
      @open="openHandler"
      @close="closeHandler"
    >
    <div style="height:600px">
<!--      <h4 style="text-align: center">{{ title }}</h4>-->

      <el-tabs v-model="taskSelectedTab">
        <el-tab-pane label="表单信息" name="form-first" class="detail">
          <component
            :formReadOnly="formReadOnly"
            v-if="formType === '2'"
            :class="formReadOnly ? 'readonly' : ''"
            ref="form"
            :businessId="businessId"
            :is="form"
            :businessType="businessType"
          ></component>

          <PreviewForm
            v-if="formType !== '2'"
            :processDefinitionId="procDefId"
            :edit="true"
            :taskFormData="taskFormData"
            ref="form"
          />
        </el-tab-pane>
        <el-tab-pane label="流程信息" v-if="procInsId" name="form-second" class="info">
          <el-card class="box-card" shadow="hover">
<!--            <div slot="header" class="clearfix">-->
<!--              <span>流程信息</span>-->
<!--            </div>-->
            <el-timeline :reverse="true" v-if="histoicFlowList.length">
              <el-timeline-item
                color="#3f9eff"
                :key="index"
                v-for="(act, index) in histoicFlowList"
                :timestamp="moment(act.histIns.endTime).format('YYYY-MM-DD')"
                placement="top"
              >
                <el-card>
                  <h4>{{ act.histIns.activityName }}</h4>
                  <p>{{ act.assigneeName }} : {{ act.comment }}</p>
                  <p>
                    开始时间 :
                    {{
                      moment(act.histIns.startTime).format(
                        "YYYY-MM-DD HH:mm:ss"
                      )
                    }}
                  </p>
                  <p>
                    结束时间 :
                    {{
                      moment(act.histIns.endTime).format("YYYY-MM-DD HH:mm:ss")
                    }}
                  </p>
                  <p>用时 : {{ act.durationTime || "0秒" }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="form-third">
          <el-card class="box-card" shadow="hover">
            <flow-chart
              ref="chart1"
              v-if="procInsId"
              :processInstanceId="procInsId"
            />
           <flow-chart
              ref="chart2"
              v-if="!procInsId"
              :processDefId="procDefId"
            />
          </el-card>
        </el-tab-pane>
        <el-tab-pane class="record" label="流转记录" v-if="procInsId" name="form-forth">
          <el-card class="box-card" shadow="hover" style="margin-top: 5px">
<!--            <div slot="header" class="clearfix">-->
<!--              <span>流转记录</span>-->
<!--            </div>-->
            <el-steps :active="histoicFlowList.length">
              <el-step
                :key="index"
                v-for="(act, index) in histoicFlowList"
                :title="act.histIns.activityName"
                finish-status="success"
                :description="
                  (act.assigneeName || '') +
                  '    ' +
                  moment(act.histIns.endTime).format('YYYY-MM-DD HH:mm:ss')
                "
              ></el-step>
            </el-steps>
            <el-table border :data="histoicFlowList" style="width: 100%;margin-top: 10px">
              <el-table-column
                prop="histIns.activityName"
                label="执行环节"
                min-width="120"
              >
              </el-table-column>
              <el-table-column prop="assigneeName" label="执行人" min-width="100">
                <template slot-scope="scope">
                  {{scope.row.assigneeName | noValue}}
                </template>
              </el-table-column>
              <el-table-column prop="histIns.startTime" label="开始时间" min-width="170">
                <template slot-scope="scope">
                  {{ scope.row.histIns.startTime | formatDate }}
                </template>
              </el-table-column>
              <el-table-column prop="histIns.endTime" label="结束时间" min-width="170">
                <template slot-scope="scope">
                  {{ scope.row.histIns.endTime | formatDate }}
                </template>
              </el-table-column>
              <el-table-column prop="comment" label="审批意见" min-width="120">
                  <template slot-scope="scope">
                      {{scope.row.comment | noValue}}
                  </template>
              </el-table-column>
              <el-table-column prop="durationTime" label="任务历时">
                <template slot-scope="scope">
                  {{ scope.row.durationTime || "0秒" }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
      </el-tabs>

      <el-card style="margin-top: 10px" v-if="!procInsId || taskId">
        <el-form :model="auditForm" ref="auditForm" label-width="120px">
          <el-col :span="16">
            <el-form-item v-if="!procInsId" label="流程标题" prop="title">
              <el-input placeholder="请输入流程标题" v-model="title">
              </el-input>
            </el-form-item>
            <el-form-item v-if="taskId" label="审批信息" prop="comment">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入审批意见"
                v-model="auditForm.comment"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item>
              <el-checkbox v-model="isCC">是否抄送</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item
              v-if="isCC"
              :rules="[
                { required: true, message: '用户不能为空', trigger: 'blur' },
              ]"
              prop="userIds"
              label="抄送给"
            >
              <user-select
                :value="auditForm.userIds"
                @getValue="
                  (value) => {
                    auditForm.userIds = value;
                  }
                "
                >></user-select
              >
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item>
              <el-checkbox v-model="isAssign"
                >指定下一步处理者(不设置就使用默认处理人)</el-checkbox
              >
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item
              v-if="isAssign"
              :rules="[
                { required: true, message: '用户不能为空', trigger: 'blur' },
              ]"
              prop="assign"
              label="指定"
            >
              <user-select
                :limit="1"
                :value="auditForm.assign"
                @getValue="
                  (value) => {
                    auditForm.assign = value;
                  }
                "
                >></user-select
              >
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item>
              <el-button
                type="primary"
                v-for="(button, index) in buttons"
                :key="index"
                @click="submit(button, buttons)"
                v-noMoreClick
                >{{ button.name }}</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-card>

    </div>
    </el-dialog>
  </div>
</template>

<script>
// import FlowChart from '../modeler/FlowChart'
import UserSelect from "@/components/userSelect";
import PreviewForm from "@/views/modules/flowable/form/GenerateFlowableForm";
import pick from "lodash.pick";
const _import = require("@/router/import-" + process.env.NODE_ENV);
export default {
  props: {
    businessType: {
        type: Number
    },
    flowTitle: {
      type: String,
      required: true,
    },
    procInsId:{
      type: String,
      required: true,
    },
    flow:{
      type: Object,
      default () {
        return {
          id:"",
          formType:"",
          formReadOnly:false,
          procInsId:"",
          procDefId:"",
          procDefKey:"",
          businessTable:"",
          businessId:"",
          isNextGatewaty:false,
          formUrl:"",
          procDefName:"",
          durationTime:"",
          todoTask:false,
          finishTask:false,
          startTask:false
        }
      }

    }


    },
  data() {
    return {

      flow1:{
        id:"",
        formType:"",
        formReadOnly:false,
        procInsId:"",
        procDefId:"",
        procDefKey:"",
        businessTable:"",
        businessId:"",
        isNextGatewaty:false,
        formUrl:"",
        procDefName:"",
        durationTime:"",
        todoTask:false,
        finishTask:false,
        startTask:false
      },
      form: null,
      detailsVisible: false,
      formType: "",
      formUrl: "",
      taskSelectedTab: "frist",
      histoicFlowList: [],
      procDefId: "",
      procInsId1:'',
      formReadOnly: false,
      procDefKey: "",
      taskId: "",
      taskFormData: [],
      taskDefKey: "",
      status: "",
      title: "",
      businessId: "",
      buttons: [],
      isCC: false,
      isAssign: false,
      auditForm: {
        comment: "",
        userIds: null,
        assign: null,
      },
    };
  },
  watch: {
    procInsId(newV,oldV){
      console.log(oldV)
      this.procInsId1=newV
      console.log(this.procInsId1)

    },
    isAssign(val) {
      if (!val) {
        this.assign = null;
      }
    },
    taskSelectedTab(val) {
      if (val === "form-third") {
        if (this.procInsId) {
          this.$refs.chart1.init();
        } else {
          this.$refs.chart2.init();
        }
      }
    },
    deep: true,
    immediate: true
  },
  activated() {},
  components: {
    UserSelect,
    PreviewForm,
    // FlowChart
  },
  methods: {
    init() {
      this.taskSelectedTab = "form-first";
      this.procDefId = this.flow1.procDefId;
      this.procDefKey = this.flow1.procDefKey;
      this.formType = this.flow1.formType;
      this.formUrl = this.flow1.formUrl;
      this.taskId = this.flow1.taskId;
      this.taskDefKey = this.flow1.taskDefKey;
      this.status = this.flow1.status;
      this.title = this.flow1.formTitle;
      this.businessId = this.flow1.businessId;
      this.procInsId1 = this.flow1.procInsId;
      this.isCC = false
      this.isAssign = false
      this.auditForm.assign = null
      this.auditForm.userIds = null
      this.auditForm.comment = "";
    },
    //取消弹框
    closeHandler(){
      this.detailsVisible=false
      console.log('取消')
    },
    //打开弹框
    openHandler() {
      console.log(this.procInsId1)
      this.$http.get('/flowable/task/getTaskDefByProcInsId', {params: {
          procInsId: this.procInsId1
        }}).then(({data}) => {
        if (data.success) {
          this.flow1 = data.flow
          console.log("激活");
          this.init();
          console.log(123);
          if (this.formType === "2") {
            console.log(1234);
            if (this.formUrl === "/404") {
              this.form = null;
              this.$message.info("没有关联流程表单!");
            } else {
              console.log(123123123);
              console.log(this.formUrl);
              this.form = _import(`modules${this.formUrl}`);
              console.log(this.form);
            }
          } else {
            // 读取流程表单
            if (this.formUrl === "/404") {
              this.$nextTick(() => {
                this.$refs.form.createForm("");
              });
            } else {
              this.$nextTick(() => {
                this.$refs.form.createForm(this.formUrl);
              });
            }
            if (this.status === "start") {
              // 读取启动表单配置
              this.$http
                .get("/flowable/form/getStartFormData", {
                  params: { processDefinitionId: this.procDefId },
                })
                .then(({ data }) => {
                  this.taskFormData = data.startFormData;
                  console.log(2222);
                  console.log(this.procDefId);
                  console.log(this.taskFormData);
                });
            } else {
              console.log(111);
              console.log(this.taskId);
              // 读取任务表单配置
              this.$http
                .get("/flowable/form/getTaskFormData", {
                  params: { taskId: this.taskId },
                })
                .then(({ data }) => {
                  this.taskFormData = data.taskFormData;
                });
            }

          }
          // 读取按钮配置
          if (this.status === "start") {
            this.buttons = [{ id: "start", name: "启动", isHide: "0" }];
          } else if (this.procDefKey && this.taskDefKey) {
            // 读取按钮
            this.$http
              .get("/extension/taskDefExtension/queryByDefIdAndTaskId", {
                params: {
                  processDefId: this.procDefKey,
                  taskDefId: this.taskDefKey,
                },
              })
              .then(({ data }) => {
                if (data.success) {
                  this.buttons = data.taskDefExtension.flowButtonList;
                }
              });
          }
          // 读取历史任务列表
          this.$http
            .get(`/flowable/task/histoicFlowList?procInsId=${this.procInsId1}`)
            .then(({ data }) => {
              this.histoicFlowList = data.histoicFlowList;
            });
        }
      })
    },
    cc(data) {
      if (this.isCC && this.auditForm.userIds) {
        this.$refs["auditForm"].validate((valid) => {
          if (valid) {
            this.$http.post("/extension/flowCopy/save", {
              userIds: this.auditForm.userIds,
              procDefId: this.procDefId,
              procInsId: data.procInsId1,
              procDefName: "",
              procInsName: this.title,
              taskName: "",
            });
          }
        });
      }
    },
    submit(currentBtn, buttons) {
      let vars = {};
      buttons.forEach((btn) => {
        if (btn.code) {
          vars[btn.code] = false;
        }
      });
      // 当前按钮的编码对应的流程变量值设置为true，其余按钮编码对应的流程变量值为false
      if (currentBtn.code) {
        vars[currentBtn.code] = true;
      }
      vars.title = this.title;
      vars.assign = this.auditForm.assign;
      if (currentBtn.id === "start") {
        if (this.formType === "2") {
          console.log(211122);
          this.$nextTick(() => {
            this.$refs.form.saveForm((businessTable, businessId) => {
              this.$http
                .post("/flowable/task/start", {
                  procDefKey: this.procDefKey,
                  businessTable: businessTable,
                  businessId: businessId,
                  ...vars,
                  title: this.title,
                  assign: this.auditForm.assign,
                })
                .then(({ data }) => {
                  if (data.success) {
                    this.$message.success(data.msg);
                    this.$events.$emit("closeTab", this.$route.fullPath);
                    this.$router.push("/flowable/task/TodoList");
                    this.cc(data);
                  }
                });
            });
          });
        } else {
          this.$nextTick(() => {
            this.$refs.form.submitStartFormData(
              {
                processDefinitionId: this.procDefId,
                ...vars,
                title: this.title,
                assign: this.auditForm.assign,
              },
              (data) => {
                if (data.success) {
                  this.$events.$emit("closeTab", this.$route.fullPath);
                  this.$router.push("/flowable/task/TodoList");
                  this.cc(data);
                }
              }
            );
          });
        }
      } else {
        if (this.formType === "2") {
          console.log(222);
          this.$http
            .post("/flowable/task/audit", {
              taskId: this.taskId,
              taskDefKey: this.taskDefKey,
              procInsId: this.procInsId1,
              procDefId: this.procDefId,
              vars: vars,
              comment: this.auditForm.comment,
              assign: this.auditForm.assign,
            })
            .then(({ data }) => {
              if (data.success) {
                this.$message.success(data.msg);
                this.$events.$emit("closeTab", this.$route.fullPath);
                this.$router.push("/flowable/task/TodoList");
                this.cc(data);
              }
            });
          // this.$refs.form.saveForm((businessTable, businessId) => {
          //
          // })
        } else {
          this.$nextTick(() => {
            this.$refs.form.submitTaskFormData(
              vars,
              this.procInsId1,
              this.taskId,
              this.auditForm.assign,
              this.auditForm.comment,
              (data) => {
                if (data.success) {
                  this.$events.$emit("closeTab", this.$route.fullPath);
                  this.$router.push("/flowable/task/TodoList");
                  this.cc(data);
                }
              }
            );
          });
        }
      }
    },
  }
};
</script>
<style lang="scss" scoped>
    @import '@/assets/scss/config.scss';
 ::v-deep .el-dialog > .el-dialog__body {
    padding: 10px 20px !important;
        padding-bottom: 20px;
    padding-bottom: 10px !important;
   .detail{
     .el-form{
       margin-top: 15px;
     }
     .el-input__inner{
       width: 320px;
     }
   }
   .el-tabs{
      margin-top: -10px;
     .el-tabs__item{
       font-size: 16px;
     }
     .box-card{
         p{
             margin: 10px 0;
         }
       ul{
         padding-left: 0;
       }

     }
       .info{
           .el-timeline{
               .el-timeline-item:last-child{
                   padding-bottom: 10px;
               }
               .el-timeline-item__node--normal{
                   background-color: $--color-primary-liyu !important;
               }
               .el-timeline-item__timestamp.is-top{
                   margin-bottom: 10px;
               }
           }
           h4{
               margin: 0;
           }
           p:last-child{
               margin-bottom: 0;
           }
       }
     .record{
       .el-table{
         th:first-child .cell,td:first-child .cell{
           text-align: left;
           padding: 0 10px;
         }

       }
     }
   }

}
</style>
